package com.ddxz.elastic.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.ddxz.elastic.job.DdxzSimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2021/2/23
 */

@Configuration
public class SimpleJobConfig {
    @Autowired
    private ZookeeperRegistryCenter regCenter;

    @Autowired
    private JobEventConfiguration jobEventConfiguration;

    @Autowired
    private DdxzElasticListener listener;

    @Bean()
    public SimpleJob simpleJob() {
        return new DdxzSimpleJob();
    }

    @Bean
    public JobScheduler simpleJobScheduler(final SimpleJob simpleJob) {
        LiteJobConfiguration configuration = getLiteJobConfiguration(simpleJob.getClass(), "0/5 * * * * ?", 3, "0=Beijing,1=Shanghai,2=Guangzhou");
        return new SpringJobScheduler(simpleJob, regCenter, configuration, jobEventConfiguration, listener);
    }

    /**
     * 构建任务的配置信息
     * @param jobClass 任务执行类
     * @param cron 执行周期
     * @param shardingTotalCount 任务分片数
     * @param shardingItemParameters 每个分片对应的参数，逗号分隔
     * @return 任务配置
     */
    private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> jobClass, final String cron, final int shardingTotalCount, final String shardingItemParameters) {
        return LiteJobConfiguration.newBuilder(
                new SimpleJobConfiguration(
                        JobCoreConfiguration.newBuilder("ddxzSimpleName", cron, shardingTotalCount)
                                .shardingItemParameters(shardingItemParameters)
                                // 设定任务的描述信息，无特殊含义
                                .description("lsfksdflsdgkrjgre")
                                // 设定任务级的参数，
                                .jobParameter("===1=====2=========3========4")
                                // 添加自定义属性，在任务执行中未获取到这些自定义的参数
                                .jobProperties("key1", "value1")
                                .jobProperties("key2", "value2")
                                .build(), jobClass.getCanonicalName()))
                .overwrite(true).build();
    }
}
